package com.chromatic.competition.view.profile;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chromatic.competition.R;
import com.chromatic.competition.model.UserInformation;
import com.chromatic.competition.utils.UserManager;
import com.chromatic.competition.utils.UserLoginStatus;

public class MyUserInfoActivity extends AppCompatActivity {
    private final UserManager manager = new UserManager();
    private EditText nicknameEditText, realnameEditText, studentIdEditText,
            cityEditText, collegeEditText, majorEditText, locationEditText;
    private RadioButton radioButtonMale, radioButtonFemale;
    private AutoCompleteTextView autoCompleteTextViewProvince, autoCompleteTextViewUniversity;
    private Spinner gradeSpinner;
    private ArrayAdapter<String> gradeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_information);

        initView();
        initAdapters();

        // assuming you're getting userId from somewhere (intent or saved instance state)
        UserLoginStatus userLoginStatus = new UserLoginStatus(this);
        int userId = userLoginStatus.getCurrentUserId();

        getUserInformation(userId);

        Button saveButton = findViewById(R.id.saveButton);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserInformation(userId);
            }
        });

        ImageView backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 调用系统返回操作
            }
        });
    }
    private void initView() {
        nicknameEditText = findViewById(R.id.editTextNickname);
        realnameEditText = findViewById(R.id.editTextRealname);
        studentIdEditText = findViewById(R.id.editTextStudentId);

        autoCompleteTextViewProvince = findViewById(R.id.autoCompleteTextViewProvince);
        cityEditText = findViewById(R.id.editTextCity);
        autoCompleteTextViewUniversity = findViewById(R.id.autoCompleteTextViewUniversity);
        collegeEditText = findViewById(R.id.editTextCollege);

        radioButtonMale = findViewById(R.id.radioButtonMale);
        radioButtonFemale = findViewById(R.id.radioButtonFemale);

        gradeSpinner = findViewById(R.id.spinnerGrade);
        majorEditText = findViewById(R.id.editTextMajor);
        locationEditText = findViewById(R.id.editTextLocation);
    }

    private void initAdapters() {
        gradeAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item,
                new String[] {"2019", "2020", "2021", "2022", "2023", "2024"}
        );
        gradeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        gradeSpinner.setAdapter(gradeAdapter);

        String[] universitiesArray = getResources().getStringArray(R.array.university_array);
        ArrayAdapter<String> universitiesAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_dropdown_item_1line, universitiesArray
        );
        autoCompleteTextViewUniversity.setAdapter(universitiesAdapter);

        String[] provincesArray = getResources().getStringArray(R.array.province_array);
        ArrayAdapter<String> provincesAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_dropdown_item_1line, provincesArray
        );
        autoCompleteTextViewProvince.setAdapter(provincesAdapter);
    }
    private void getUserInformation(int userId) {
        UserManager.getUserInformation(userId, new UserManager.UserInformationCallback() {
            @Override
            public void onSuccess(UserInformation userInformation) {
                nicknameEditText.setText(userInformation.getNickname());
                realnameEditText.setText(userInformation.getRealname());
                studentIdEditText.setText(userInformation.getStudentId());

                RadioGroup radioGroupGender = findViewById(R.id.radioGroupGender);
                if ("男".equals(userInformation.getGender())) {
                    radioGroupGender.check(radioButtonMale.getId());
                } else if ("女".equals(userInformation.getGender())) {
                    radioGroupGender.check(radioButtonFemale.getId());
                }

                autoCompleteTextViewProvince.setText(userInformation.getProvince(), true);
                cityEditText.setText(userInformation.getCity());
                autoCompleteTextViewUniversity.setText(userInformation.getUniversity(), true);
                collegeEditText.setText(userInformation.getCollege());

                int position = gradeAdapter.getPosition(userInformation.getGrade());
                gradeSpinner.setSelection(position);

                majorEditText.setText(userInformation.getMajor());
                locationEditText.setText(userInformation.getLocation());
            }
            @Override
            public void onError(String errorMessage) {
//                Log.d("MyUserInfoActivity的getUserInformation方法","错误信息：" + errorMessage);
                Toast.makeText(MyUserInfoActivity.this, "Error getting user info: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }

    private void updateUserInformation(int userId) {
        // 获取完整的个人资料
        UserManager.getUserInformation(userId, new UserManager.UserInformationCallback() {
            @Override
            public void onSuccess(UserInformation userInformation) {
                // 更新个人资料的相关字段
                userInformation.setNickname(nicknameEditText.getText().toString());
                userInformation.setRealname(realnameEditText.getText().toString());
                userInformation.setStudentId(studentIdEditText.getText().toString());

                RadioGroup radioGroupGender = findViewById(R.id.radioGroupGender);
                int selectedId = radioGroupGender.getCheckedRadioButtonId();
                String selectedGender = "";
                if (selectedId == R.id.radioButtonMale) {
                    selectedGender = "男";
                } else if (selectedId == R.id.radioButtonFemale) {
                    selectedGender = "女";
                }
                userInformation.setGender(selectedGender);

                userInformation.setProvince(autoCompleteTextViewProvince.getText().toString());
                userInformation.setCity(cityEditText.getText().toString());
                userInformation.setUniversity(autoCompleteTextViewUniversity.getText().toString());
                userInformation.setCollege(collegeEditText.getText().toString());

                userInformation.setGrade(gradeSpinner.getSelectedItem().toString());

                userInformation.setMajor(majorEditText.getText().toString());
                userInformation.setLocation(locationEditText.getText().toString());

                // 调用更新用户信息的方法
                manager.updateUserInformation(userId, userInformation, new UserManager.UserInformationCallback() {
                    @Override
                    public void onSuccess(UserInformation updatedUserInformation) {
                        Toast.makeText(MyUserInfoActivity.this, "用户资料更新成功！", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(String errorMessage) {
                        Toast.makeText(MyUserInfoActivity.this, "用户资料更新出错: " + errorMessage, Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onError(String errorMessage) {
                Toast.makeText(MyUserInfoActivity.this, "获取用户信息失败: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }
}